package com.hutu.erp.catalog.controller;

import java.util.ArrayList;
import java.util.List;

import com.hutu.erp.catalog.domain.ProductPicture;
import com.hutu.erp.catalog.dto.ProductPictureResult;
import com.hutu.erp.catalog.map.CatalogMap;
import com.hutu.erp.catalog.map.SystemObjectMapper;
import com.hutu.erp.catalog.model.PictureModel;
import com.hutu.erp.catalog.model.ProductModel;

import com.hutu.erp.catalog.model.ProductPictureModel;
import com.hutu.erp.catalog.service.IProductPictureService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.IPictureService;

import com.ruoyi.system.domain.Picture;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.hutu.erp.catalog.domain.Product;
import com.hutu.erp.catalog.service.IProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 商品Controller
 * 
 * @author ruoyi
 * @date 2021-05-24
 */
@RestController
@RequestMapping("/catalog/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;

    @Autowired
    private IPictureService pictureService;

    @Autowired
    private IProductPictureService productPictureService;

    @Resource
    private CatalogMap catalogMap;

    @Resource
    private SystemObjectMapper systemObjectMapper;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Product product)
    {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        return util.exportExcel(list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId)
    {
        Product product = productService.selectProductById(productId);
        ProductModel model = catalogMap.toProductModel(product);

        return AjaxResult.success(model);
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductModel model)
    {
//        return toAjax(productService.insertProduct(product));
        Product  product = catalogMap.toProduct(model);
        int val = productService.insertProduct(product);

        List<ProductPictureModel> pictures = model.getPictureList();
        if(pictures != null && pictures.size() > 0)
        {
            for (int i = 0; i < pictures.size(); i++) {
                ProductPictureModel pictureModel = pictures.get(i);
                productService.insertProductPicture(new ProductPicture (null,
                    product.getProductId(),
                    pictureModel.getPictureId(),
                    i + 1
                ));
            }
        }

        return toAjax(val);
    }


    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductModel model)
    {
        Product  product = catalogMap.toProduct(model);
        if(model.isChangeCover()){
            PictureModel coverModel = model.getCover();
            if(coverModel != null){
                Picture picture = systemObjectMapper.toPicture(coverModel);
                picture.setCreatedBy(SecurityUtils.getUsername());
                int i = pictureService.insertPicture(picture);
                System.out.println("插入图片的自增Id： " + picture.getPictureId());
                product.setCoverId(picture.getPictureId());
            }
        }
        int val = productService.updateProduct(product);
        return toAjax(val);
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        return toAjax(productService.deleteProductByIds(productIds));
    }

    // region

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('catalog:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("picture")
    // public AjaxResult addPicture(@RequestBody PictureModel model)
    public AjaxResult addPicture(@RequestBody ProductPictureModel model)
    {
//        Picture picture = systemObjectMapper.toPicture(model);
//        picture.setCreatedBy(SecurityUtils.getUsername());
//        int i = pictureService.insertPicture(picture);
//        System.out.println("插入图片的自增Id： " + picture.getPictureId());
        //product.setCoverId(picture.getPictureId());

        ProductPictureResult result = productService.insertProductPicture(model);
        AjaxResult resopnseModel = AjaxResult.success();
        resopnseModel.put("productPictureId", result.getProductPictureId());
        resopnseModel.put("productId", result.getProductId());
        resopnseModel.put("pictureId", result.getPictureId());
        resopnseModel.put("displayOrder", result.getDisplayOrder());
        resopnseModel.put("url", result.getUrl());
        return resopnseModel;
    }
    @PreAuthorize("@ss.hasPermi('catalog:product:edit')")
//    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PutMapping("picture/{productPictureId}")
    // public AjaxResult addPicture(@RequestBody PictureModel model)
    public AjaxResult updatePicture(@PathVariable Integer productPictureId, @RequestBody ProductPictureModel model)
    {
//        Picture picture = systemObjectMapper.toPicture(model);
//        picture.setCreatedBy(SecurityUtils.getUsername());
//        int i = pictureService.insertPicture(picture);
//        System.out.println("插入图片的自增Id： " + picture.getPictureId());
        //product.setCoverId(picture.getPictureId());

        ProductPictureResult result = productService.insertProductPicture(model);
        AjaxResult resopnseModel = AjaxResult.success();
        resopnseModel.put("pictureId", result.getPictureId());
        resopnseModel.put("url", result.getUrl());
        return resopnseModel;
    }

    @PreAuthorize("@ss.hasPermi('catalog:product:edit')")
//    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PutMapping("picture")
    // public AjaxResult addPicture(@RequestBody PictureModel model)
    public AjaxResult updatePictures(@RequestBody ArrayList<ProductPictureModel>  model)
    {
//        Picture picture = systemObjectMapper.toPicture(model);
//        picture.setCreatedBy(SecurityUtils.getUsername());
//        int i = pictureService.insertPicture(picture);
//        System.out.println("插入图片的自增Id： " + picture.getPictureId());
        //product.setCoverId(picture.getPictureId());

        if(model == null || model.size() == 0){
            return AjaxResult.error("没有发送要修改的图片");
        }

        System.out.println( "接收的图片列表：" + model.toString());

        ProductPictureResult result = productService.updateProductPictures(model);
        AjaxResult resopnseModel = AjaxResult.success();
        return resopnseModel;
    }


    @PreAuthorize("@ss.hasPermi('catalog:product:list')")
    @GetMapping("picture")
    public AjaxResult getProductPictures(long productId)
    {
        List<ProductPicture> productPictures = productService.getProductPictureList(productId);
        List<ProductPictureModel> model = new ArrayList<>();
        for(ProductPicture productPicture: productPictures){
            ProductPictureModel pictureModel = new ProductPictureModel();

            pictureModel.setProductPictureId(productPicture.getProductPictureId());
            pictureModel.setProductId(productId);
            pictureModel.setPictureId(productPicture.getPictureId());
            pictureModel.setDisplayOrder(productPicture.getDisplayOrder());

            Picture picture = pictureService.selectPictureById(productPicture.getPictureId());
            if(picture != null) {
                pictureModel.setUrl(serverConfig.getUrl() +  picture.getVirtualPath());
                pictureModel.setName(picture.getOriginalFilename());
            }
            model.add(pictureModel);
        }
//        AjaxResult ajax = AjaxResult.success(model);
        return AjaxResult.success(model);
    }

    // endregion

    // productPictureId
    @PreAuthorize("@ss.hasPermi('catalog:product_picture:remove')")
    @Log(title = "商品图片", businessType = BusinessType.DELETE)
    @DeleteMapping("picture/{productPictureId}")
    public AjaxResult deleteProductPicture(@PathVariable Long productPictureId)
    {
        return toAjax(productPictureService.deleteProductPictureById(productPictureId));
    }

}
